package com.kbt.listener;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.google.gson.Gson;
import com.kbt.activity.R;
import com.kbt.activity.StoreActivity;
import com.kbt.base.BaseApplication;
import com.kbt.commont.Constants;
import com.kbt.fragment.GoodCarEditFragment;
import com.kbt.model.data.BaseBean;
import com.kbt.model.data.CountBean;
import com.kbt.model.data.ShopCarBean;
import com.kbt.net.RequestManager;
import com.kbt.util.data.StaticData;
import com.kbt.util.utils.SharePreferenceUtils;
import com.kbt.util.utils.Utils;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author zhgk
 * @package: com.kbt.listener
 * @TODO: 增加获删除按钮事件, 用于改变商品数量
 * @data: 2015/8/11 12:43
 * @version: V1.0
 */
public class ClickChangeGoodCountListener implements View.OnClickListener,RequestManager.ResponseInterface {

    //按钮点击类型
    private int btnType = 0;
    //商品数量框
    private EditText goodCountEdit;
    //商品数量文本
    private TextView goodCountView;
    //总费用文本
    private TextView totalFeeVIew;
    //商品价张
    private double goodPrice = 0.0;

    //按钮位置，即触发页面
    private int btnPosition;

    //商品确实减少了么
    private boolean realSub = false;
    //商品件数
    private TextView numberView;
    //应付总价
    private TextView payMoneyView;
    //商品总价
    private TextView totalMoneyView;
    //判断是否选中
    private int position;
    //分数
    public static List<HashMap<String, String>> numList = null;

    private RequestManager mRequestManager;
    private Map<String, String> map =null;
    private Map<String,Object> getMap =null;
    private String id;
    private BaseBean baseBean;

    private int isAdd = 0;
    private SharePreferenceUtils share;
    private Activity activity;
    private ShopCarBean shopCarBean;
    private CountBean countBean;


    /***
     * 构造函数
     * 只处理数据增长
     *
     * @param btnType
     * @param goodCount
     */
    public ClickChangeGoodCountListener(int btnType, EditText goodCount) {
        this.btnType = btnType;
        this.goodCountEdit = goodCount;
    }

    /**
     * 处理数据增长，同时改写数量
     *
     * @param btnType
     * @param goodCount
     * @param goodCountView
     */
    public ClickChangeGoodCountListener(int btnType, EditText goodCount, TextView goodCountView, int btnPosition) {
        this.btnType = btnType;
        this.goodCountView = goodCountView;
        this.goodCountEdit = goodCount;
        this.btnPosition = btnPosition;
    }


    /**
     * 处理数据变化的同时，改写数量变化、计算总费用
     *
     * @param btnType
     * @param goodCount
     * @param goodCountView
     */

    public ClickChangeGoodCountListener(Activity activity,int btnType, EditText goodCount, TextView goodCountView, TextView totalFee,TextView numberView,TextView payMoneyView,TextView totalMoneyView, double price, int btnPosition,int position,List<HashMap<String, String>> numList,String id,ShopCarBean shopCarBean) {
        this.btnType = btnType;
        this.goodCountView = goodCountView;
        this.goodCountEdit = goodCount;
        this.totalFeeVIew = totalFee;
        this.numberView = numberView;
        this.payMoneyView = payMoneyView;
        this.totalMoneyView = totalMoneyView;
        this.goodPrice = price;
        this.btnPosition = btnPosition;
        this.position = position;
        this.numList = numList;
        this.id =id;
        mRequestManager = new RequestManager();
        mRequestManager.setResponseListener(this);
        map = new HashMap<String, String>();
        share = new SharePreferenceUtils(activity);
        this.activity = activity;
        this.shopCarBean = shopCarBean;
        getMap = new HashMap<String,Object>();
    }

    @Override
    public void onClick(View v) {
        switch (btnType) {
            case StaticData.BUTTON_ADD_BTN:

                if (btnPosition == StaticData.CHANG_EDIT_SHOW_COUNT) {
                    addGoodCount();
                    addGoodShowCount(goodCountEdit);
                } else if (btnPosition == StaticData.CHANG_EDIT_SHOW_TOTAL_COUNT) {
                    addGoodCount();
                    addGoodShowCount(goodCountEdit);
                    addGoodTotalFee();
                } else {
                    addGoodCount();
                }

                break;
            case StaticData.BUTTON_SUB_BTN:

                if (btnPosition == StaticData.CHANG_EDIT_SHOW_COUNT) {
                    subGoodCount();
                    subGoodShowCount(goodCountEdit);
                } else if (btnPosition == StaticData.CHANG_EDIT_SHOW_TOTAL_COUNT) {
                    subGoodCount();
                    subGoodShowCount(goodCountEdit);
                    subGoodTotalFee();
                } else {
                    subGoodCount();
                }

                break;
            default:
                break;
        }

    }

    /**
     * 增加商品数量
     */
    private void addGoodCount() {
        isAdd = 1;
        String countStr = goodCountEdit.getText().toString().trim();
        countStr = countStr.length() == 0 ? "0" : countStr;
        int count = Integer.valueOf(countStr);
        count++;
        goodCountEdit.setText(String.valueOf(count));
        int number = 0;
        if(numList!=null) {
            number  = Integer.parseInt(numList.get(position).get("number")) + 1;
            numList.get(position).put("number", "" + number);
        }
//        //改变选中购物车中物品的数量
//        for(int i=0;i<BaseApplication.getInstance().goodForCarInfos.size();i++){
//           if(BaseApplication.getInstance().goodForCarInfos.get(i).getSign()==position){
//               String old_count = BaseApplication.getInstance().goodForCarInfos.get(i).getGoods_count();
//               int new_count = Integer.parseInt(old_count)+1;
//               BaseApplication.getInstance().goodForCarInfos.get(i).setGoods_count(new_count+"");
//           }
//        }
        //增加时更新数据
        httpAddORJian("1");


    }
    //增加时更新数据
    private void httpAddORJian(String count){
        if(Utils.isNetworkAvailable(activity)) {
            map.clear();
            map.put("methodType", "update");
            Gson gson = new Gson();
            Map dataMap = new HashMap<String,String>();
            dataMap.put("user_mobile", share.getString("user_mobile", ""));
            dataMap.put("goods_count", count);
            dataMap.put("goods_id", id);
            map.put("data", gson.toJson(dataMap));
            mRequestManager.post(Constants.ServiceInterFace.addOrJianShopCarURL, map, Constants.RequestTag.addOrJianShopCarTag, BaseBean.class);
        }else{
           Toast.makeText(activity, R.string.Wangluo,Toast.LENGTH_SHORT).show();
        }
    }

    /***
     * 减少商品数量
     */
    private void subGoodCount() {
        isAdd=2;
        String countStr = goodCountEdit.getText().toString().trim();
        countStr = countStr.length() == 0 ? "0" : countStr;
        int count = Integer.valueOf(countStr);
        if (count > 1) {
            count--;
            realSub = true;
        } else {
            realSub = false;
        }
        goodCountEdit.setText(String.valueOf(count));
        int number=0;
        if(numList!=null) {
            number = Integer.parseInt(numList.get(position).get("number")) - 1;
            numList.get(position).put("number", "" + number);
        }//改变选中购物车中物品的数量
//        for(int i=0;i<BaseApplication.getInstance().goodForCarInfos.size();i++){
//            if(BaseApplication.getInstance().goodForCarInfos.get(i).getSign()==position){
//                String old_count = BaseApplication.getInstance().goodForCarInfos.get(i).getGoods_count();
//                int new_count = Integer.parseInt(old_count)-1;
//                BaseApplication.getInstance().goodForCarInfos.get(i).setGoods_count(new_count+"");
//            }
//        }
        if(number>0){
            httpAddORJian("-1");
        }

    }

    /**
     * 减少显示数量
     */
    private void subGoodShowCount(EditText editText) {
        goodCountView.setText("" + editText.getText());
    }

    /**
     * 增加显示数量
     */
    private void addGoodShowCount(EditText editText) {
        goodCountView.setText("" + String.valueOf(editText.getText()));
    }

    /**
     * 减少总数量
     */
    private void subGoodTotalFee() {

        if (realSub) {
            if(shopCarBean.getGoods_status().equals("1")) {
                String countStr = totalFeeVIew.getText().toString().trim();
                countStr = countStr.length() == 0 ? "0" : countStr;
                double fee = Float.valueOf(countStr) - goodPrice;
                BaseApplication.getInstance().shopCarTotal = fee;
                BaseApplication.getInstance().shopCarNumber -= 1;
                double price = BaseApplication.getInstance().shopCarTotal - BaseApplication.getInstance().freight + BaseApplication.getInstance().discount;
                BaseApplication.getInstance().shopCarPayable = price;
                numberView.setText("已选择商品" + BaseApplication.getInstance().shopCarNumber + "件");
                totalFeeVIew.setText(new BigDecimal(price).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                totalMoneyView.setText(new BigDecimal(fee).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                payMoneyView.setText(new BigDecimal(price).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
            }
        }
        realSub = false;
    }

    /***
     * 增加总数量
     */
    private void addGoodTotalFee() {
        if (shopCarBean.getGoods_status().equals("1")) {
            String countStr = totalFeeVIew.getText().toString().trim();
            countStr = countStr.length() == 0 ? "0" : countStr;
            double fee = Float.valueOf(countStr) + goodPrice;
            BaseApplication.getInstance().shopCarTotal = fee;
            BaseApplication.getInstance().shopCarNumber += 1;
            double price = BaseApplication.getInstance().shopCarTotal - BaseApplication.getInstance().freight + BaseApplication.getInstance().discount;
            BaseApplication.getInstance().shopCarPayable = price;
            numberView.setText("已选择商品" + BaseApplication.getInstance().shopCarNumber + "件");
            totalFeeVIew.setText(new BigDecimal(price).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
            totalMoneyView.setText(new BigDecimal(fee).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
            payMoneyView.setText(new BigDecimal(price).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        }
    }


    @Override
    public <T> void successResponse(T parsedGSON, int tag) {
        if (tag == Constants.RequestTag.addOrJianShopCarTag) {
            /** 判断返回值不为空 **/
            if (parsedGSON != null) {
                baseBean = (BaseBean) parsedGSON;
                if (baseBean.getResult().equals("success")) {
                    getShopType();
                } else {
                    if (isAdd == 1) {
                        int number = Integer.parseInt(numList.get(position).get("number")) - 1;
                        numList.get(position).put("number", "" + number);
                        goodCountEdit.setText(String.valueOf(number));
                    } else if (isAdd == 2) {
                        int number = Integer.parseInt(numList.get(position).get("number")) + 1;
                        numList.get(position).put("number", "" + number);
                        goodCountEdit.setText(String.valueOf(number));
                    }
                }
            }
        }
        if (tag == Constants.RequestTag.selectShopCarZhongLeiTag) {
            if (parsedGSON != null) {
                countBean = (CountBean) parsedGSON;
                // 判断是否是有数据
                if (countBean.getResult().equals("success")) {// 成功
                    BaseApplication.getInstance().shopType = countBean.getData();
                    StoreActivity.jianCarNumber();
                }
            }
        }
    }

    @Override
    public void errorResonse(String retmeg, int tag) {
        Toast.makeText(activity,R.string.noWangluo,Toast.LENGTH_SHORT).show();
    }
    //获取商品数量
    private void getShopType(){
        if(Utils.isNetworkAvailable(activity)){
            mRequestManager.requestGet(Request.Method.GET, Constants.ServiceInterFace.selectShopCarZhongLeiURL + share.getString("user_mobile","")+"&methodType=queryGoodsSum", Constants.RequestTag.selectShopCarZhongLeiTag,getMap, CountBean.class);
        }else{
            Toast.makeText(activity,R.string.Wangluo,Toast.LENGTH_SHORT).show();
        }
    }
}
